<template>
  <div class="setrole">
    <el-dialog :title="'为【' + username + '】分配权限'" :visible="show">
      <el-tree
        :data="list"
        ref="mytree"
        default-expand-all
        show-checkbox
        node-key="id"
        :check-strictly="true"
        :props="propsObj"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionAllApi } from '@/api/permission'
import { getRoleDetailAPI, setRolePermissionApi } from '@/api/setting'
export default {
  props: ['username', 'show'],
  data () {
    return {
      list: [],
      propsObj: {
        label: 'name'
      },
      id: '',
      permIds: ''
    }
  },
  methods: {
    async getPermissionAll () {
      const res = await getPermissionAllApi()
      this.list = this.turnData(res.data, '0')
    },
    async getRoleDetail (id) {
      this.id = id
      const res = await getRoleDetailAPI(id)
      this.permIds = res.data.permIds
      this.$refs.mytree.setCheckedKeys(this.permIds)
    },
    turnData (arr, pid) {
      const newArr = []
      arr.forEach(item => {
        if (item.pid === pid) {
          const children = this.turnData(arr, item.id)
          if (children.length > 0) {
            item.children = children
          }
          newArr.push(item)
        }
      })
      return newArr
    },
    cancle () {
      this.$emit('update:show', false)
    },
    async submit () {
      const res = this.$refs.mytree.getCheckedKeys()
      console.log(res)
      console.log(this.id)
      console.log(this.permIds)
      await setRolePermissionApi({
        id: this.id,
        permIds: res
      })
      this.$message.success('分配权限成功')
      this.$emit('update:show', false)
    }
  },
  created () {
    this.getPermissionAll()
  }
}
</script>

<style lang="scss"></style>
